package gu.simplemq;

import gu.simplemq.exceptions.SmqRuntimeException;

/**
 * simplemq运行上下文对象
 * @author guyadong
 *
 */
public class SimplemqContext {
	public static final ThreadLocal<SimplemqContext> context = new ThreadLocal<>();

	Channel<?> currentChannel ;
	MessageAck messageAck;
	SimplemqContext() {
	}
	/**
	 * 用指定的 Channel 设置上下文对象
	 * @param currentChannel
	 */
	static void setChannel(Channel<?> currentChannel){
		getCurrentContext().currentChannel = currentChannel;
	}

	public String getCurrentChannelName(){
		return currentChannel != null ? currentChannel.name : null;
	}
	public Channel<?> getCurrentChannel(){
		return currentChannel;
	}
	public MessageAck getMessageAck() {
		return messageAck;
	}
	public SimplemqContext setMessageAck(MessageAck messageAck) {
		this.messageAck = messageAck;
		return this;
	}
	/**
	 * 手动发送消息确认(ACK)
	 * @throws SmqRuntimeException
	 */
	public void acknowledge() throws SmqRuntimeException{
		if(null != messageAck) {
			messageAck.acknowledge();
		}
	}
	/**
	 * @since 2.3.9
	 */
	public static SimplemqContext getCurrentContext() {
		SimplemqContext c;
		if((c = context.get()) == null){
			c = new SimplemqContext();
			context.set(c);
		}
		return c;
	}
	public static void setCurrentContext(SimplemqContext c) {
		context.set(c);
	}
}
